package com.zxd.gateway.com.zxd.conf;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * ClassName:Configuration
 * Package:com.zxd.gateway.com.zxd.conf
 *
 * @Date:2024/3/20 22:42
 * @Author:zxde
 */
@Component
public class Configuration implements GlobalFilter, Ordered {

    @Value(value = "${auth.authValue}")
    private String authValue;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String authkey = queryParams.getFirst("auth");
        if (Objects.equals(authkey, authValue)) {
            Mono<Void> filter = chain.filter(exchange);
            return filter;
        }
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
